// pages/profile/index.ts
const app = getApp()
Page({
  data: {
    nickName: '',
    avatar: ''
  },
  onLoad () {
    const { avatar, nickName } = app
    this.setData({ avatar, nickName })
  },
  async updataNickName (ev) {
    const res = ev.detail.value
    const { code } = await wx.http.put('/userInfo', { nickName: res })
    if (code !== 10000) return wx.utils.toast()
    this.setData({ nickName: res })
    getApp().setUserInfo('nickName', res)
  },
  updataAvatar (ev) {
    console.log(ev)
    const avatar = ev.detail.avatarUrl
    wx.uploadFile({
      // 待上传的文件路径
      filePath: avatar,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: `Bearer ${app.token}`
      },
      formData: { type: 'avatar' },
      success: res => {
        const data = JSON.parse(res.data)
        // 检测接口是否调用成功
        if (data.code !== 10000) return wx.utils.toast('上传头像失败!')
        // 借助于页面栈实例来更新 pages/my/index.wxml 中的头像
        this.setData({ avatar: data.data.url })
        app.setUserInfo('avatar', data.data.url)
      }
    })
  }
})
